//
//  BCWalletDetailController.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/11/16.
//  Copyright © 2018年 guoshikeji. All rights reserved.
//

#import "BCWalletDetailController.h"

//cells
#import "BCWalletDetailNormalCell.h"
#import "BCWalletDetailNormalTagCell.h"
#import "BCWalletDetailNotesCell.h"

//refresh
#import "BCRefreshNormalHeader.h"
#import "BCRefreshAutoFooter.h"

//
#import "BCUserWalletDataMenu.h"

//request
#import "UserWalletDetailsRequest.h"

@interface BCWalletDetailController () <UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UITableView *detailTable;

/**
 *refreshHeader
 */
@property (nonatomic, strong) BCRefreshNormalHeader *refreshHeader;

/**
 *refreshAutoFooter
 */
@property (nonatomic, strong) BCRefreshAutoFooter *refreshAutoFooter;

/**
 *detailSource
 */
@property (nonatomic, strong) NSMutableArray *detailSource;


/**
 *page 请求的页面
 */
@property (nonatomic, assign) NSInteger reqeustPage;

@end

@implementation BCWalletDetailController

- (NSMutableArray *)detailSource {
    if (!_detailSource) {
        _detailSource = [NSMutableArray array];
    }
    return _detailSource;
}

- (BCRefreshNormalHeader *)refreshHeader {
    if (!_refreshHeader) {
        _refreshHeader = [BCRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshHeaderAction)];
    }
    return _refreshHeader;
}
- (BCRefreshAutoFooter *)refreshAutoFooter {
    if (!_refreshAutoFooter) {
        _refreshAutoFooter = [BCRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshAutoFooterLoadMoreAction) needBottomSafeArea:true];
    }
    return _refreshAutoFooter;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //
    [self setupSubviews];
    //
    [self requestDetailsInit:true refresh:false loadMore:false];
}

- (void)setupSubviews {
    if (!self.singleDetail) {
        [self.customNaviBar removeFromSuperview];
    }else {
        self.title = self.title;
    }
    //
    self.detailTable = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.detailTable.separatorStyle = UITableViewCellSelectionStyleNone;
    self.detailTable.dataSource = self;
    self.detailTable.delegate = self;
    [self.view addSubview:self.detailTable];
    if (!self.singleDetail) {
        [self.detailTable mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.view);
            make.left.bottom.right.mas_equalTo(self.view);
        }];
    }else {
        [self.detailTable mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.customNaviBar.mas_bottom);
            make.left.bottom.right.mas_equalTo(self.view);
        }];
    }
    //registerCells
    NSArray *registerCells = [UserWalletDetailsDataModel registerCells];
    for (NSString *cellName in registerCells) {
        [self.detailTable registerClass:NSClassFromString(cellName) forCellReuseIdentifier:cellName];
    }
    //
    [self.detailTable setMj_header:self.refreshHeader];
    //
    [self.view layoutIfNeeded];
}

#pragma mark - UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.detailSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UserWalletDetailsDataModel *cellData = self.detailSource[indexPath.row];
    BCWalletDetailBaseCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([cellData cellClass])];
    cell.cellData = cellData;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    UserWalletDetailsDataModel *cellData = self.detailSource[indexPath.row];
    Class cellClass = [cellData cellClass];
    if (cellClass==BCWalletDetailNormalCell.class) {
        return [tableView fd_heightForCellWithIdentifier:NSStringFromClass(cellClass) configuration:^(id cell) {
            ((BCWalletDetailNormalCell *)cell).cellData = cellData;
        }];
    }else if (cellClass==BCWalletDetailNormalTagCell.class) {
        return [tableView fd_heightForCellWithIdentifier:NSStringFromClass(cellClass) configuration:^(id cell) {
            ((BCWalletDetailNormalTagCell *)cell).cellData = cellData;
        }];
    }else if (cellClass==BCWalletDetailNotesCell.class) {
        return [tableView fd_heightForCellWithIdentifier:NSStringFromClass(cellClass) configuration:^(id cell) {
            ((BCWalletDetailNotesCell *)cell).cellData = cellData;
        }];
    }
    return 0;
}

#pragma mark - refresh
- (void)refreshHeaderAction {
    [self requestDetailsInit:false refresh:true loadMore:false];
}
//loadmore
- (void)refreshAutoFooterLoadMoreAction {
    [self requestDetailsInit:false refresh:false loadMore:true];
}


#pragma mark - request
- (void)requestDetailsInit:(BOOL)init refresh:(BOOL)refresh loadMore:(BOOL)loadMore {
    if (init) {
        [self.view bc_showLoadingInsets:UIEdgeInsetsMake(CGRectGetHeight(self.customNaviBar.frame), 0, 0, 0)];
    }
    if (refresh) {
        [self.detailTable bc_hiddenError];
    }
    if (init||refresh) {
        //如果有refreshFooter 直接移除
        if (self.detailTable.mj_footer) {
            [self.detailTable setMj_footer:nil];
        }
        if (_refreshAutoFooter) {
            [_refreshAutoFooter resetNoMoreData];
        }
    }
    
    UserWalletDetailsRequest *request = [UserWalletDetailsRequest new];
    request.status = self.menuItem.status;
    if (init||refresh) {
        self.reqeustPage = 1;
        request.page = [NSString stringWithFormat:@"%@",@(self.reqeustPage)];
    }
    if (loadMore) {
        request.page = [NSString stringWithFormat:@"%@",@(self.reqeustPage+1)];
    }
    WEAK_SELF
    [request didRequestCompleted:^{
        if (init) {
            [wself.view bc_hiddenLoading];
        }
        if (refresh) {
            [wself.refreshHeader endRefreshing];
        }
        if (loadMore) {
            [wself.refreshAutoFooter endRefreshing];
        }
    }];
    [request didRequestSuccessed:^(id result, id page) {
        //如果请求成功页面 reqeustPage=
        wself.reqeustPage = request.page.integerValue;
        //
        UserWalletDetailsResponse *resp = result;
        [wself handleData:resp.data init:init refresh:refresh loadMore:loadMore];
    }];
    [request didRequestFailed:^(NSError *error) {
        if (error&&wself.view) {
            NSString *errMsg = error.domain;
            [QMUITips showError:errMsg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:errMsg]];
            //
            if (init) {
                [wself.view bc_showError:error needRefresh:true refreshTitle:nil target:wself refreshAction:@selector(requestInitErrorAction)];
            }
        }
    }];
    [request requestServer];
}
- (void)requestInitErrorAction {
    [self.view bc_hiddenError];
    [self requestDetailsInit:true refresh:false loadMore:false];
}

//请求成功处理数据
- (void)handleData:(UserWalletDetailsData *)data init:(BOOL)init refresh:(BOOL)refresh loadMore:(BOOL)loadMore {
    //做保护 可能在加载更多时 操作了刷新 那么此次加载更多数据不要直接舍弃
    if (loadMore) {
        if (!self.detailTable.mj_footer) {
            return;
        }
    }
    [self.view bc_hidderEmptyData];
    if (data) {
        UserWalletDetailsDataFlow *flow = data.flow;
        //
//        self.title = data.flow.title;
        //
        NSArray *dataSource = data.data;
        //
        if (init||refresh) {
            [self.detailSource removeAllObjects];
            //如果
            if (dataSource.count==0) {
                [self.detailTable bc_showEmptyDataInsets:UIEdgeInsetsMake(0, 0, 0, 0) text:data.flow.not_data detail:nil];
            }else {
                [self.refreshAutoFooter setTitle:data.flow.bottom forState:MJRefreshStateNoMoreData];
                if (data.more) {
                    //加入加载更多控件
                    [self.detailTable setMj_footer:self.refreshAutoFooter];
                }
            }
        }
        if (loadMore) {
            if (!data.more) {
                //显示咩有更多了
                [self.refreshAutoFooter endRefreshingWithNoMoreData];
            }
        }
        //
        for (int i=0; i<dataSource.count; i++) {
            UserWalletDetailsDataModel *model = dataSource[i];
            model.timeCaption = flow.time;
            model.numberCaption = flow.number;
            [self.detailSource addObject:model];
        }
    }
    [self.detailTable reloadData];
}




#pragma mark - pop
/// 是否需要拦截系统返回按钮的事件，只有当这里返回YES的时候，才会询问方法：`canPopViewController`
- (BOOL)shouldHoldBackButtonEvent {
    return true;
}

/// 是否可以`popViewController`，可以在这个返回里面做一些业务的判断，比如点击返回按钮的时候，如果输入框里面的文本没有满足条件的则可以弹alert并且返回NO
- (BOOL)canPopViewController {
    return self.singleDetail;
}

@end
